package cn.hdu.liang.core.service.product;

import cn.hdu.liang.core.bean.product.Product;
import cn.hdu.liang.core.bean.product.Sku;
import cn.hdu.liang.core.dao.product.SkuDao;
import cn.hdu.liang.core.query.product.SkuQuery;
import cn.itcast.common.page.Pagination;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 最小销售单元事务层
 */
@Service
@Transactional
public class SkuServiceImpl implements SkuService {

    @Resource
    private SkuDao skuDao;
    @Resource
    private ColorService colorService;
    @Resource
    private ProductService productService;

    public Integer addSku(Sku sku) {
        return skuDao.addSku(sku);
    }

    @Transactional(readOnly = true)
    public Sku getSkuByKey(Integer id) {
        Sku sku = skuDao.getSkuByKey(id);
        Product product = productService.getProductByKey(sku.getProductId());
        sku.setProduct(product);
        sku.setColor(colorService.getColorByKey(sku.getColorId()));
        return sku;
    }

    @Transactional(readOnly = true)
    public List<Sku> getSkusByKeys(List<Integer> idList) {
        return skuDao.getSkusByKeys(idList);
    }

    public Integer deleteByKey(Integer id) {
        return skuDao.deleteByKey(id);
    }

    public Integer deleteByKeys(List<Integer> idList) {
        return skuDao.deleteByKeys(idList);
    }

    public Integer updateSkuByKey(Sku sku) {
        return skuDao.updateSkuByKey(sku);
    }

    @Transactional(readOnly = true)
    public Pagination getSkuListWithPage(SkuQuery skuQuery) {
        Pagination p = new Pagination(skuQuery.getPageNo(), skuQuery.getPageSize(), skuDao.getSkuListCount(skuQuery));
        p.setList(skuDao.getSkuListWithPage(skuQuery));
        return p;
    }

    @Transactional(readOnly = true)
    public List<Sku> getSkuList(SkuQuery skuQuery) {
        List<Sku> skus = skuDao.getSkuList(skuQuery);
        for(Sku sku : skus) {
            sku.setColor(colorService.getColorByKey(sku.getColorId()));
        }
        return skus;
    }

    @Override
    public List<Sku> getStock(Integer productId) {
        List<Sku> skus = skuDao.getStock(productId);
        for(Sku sku : skus) {
            sku.setColor(colorService.getColorByKey(sku.getColorId()));
        }
        return skus;
    }
}
